//
//  LBNiuStudentDetailVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/2.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBNiuStudentDetailVC.h"
#import "LBNiuwaDetailCell.h"
#import "LBDakaDetailVC.h"
#import "WKNiuwaCell.h"
#import "LBRemenCell.h"
#import "XHWebImageAutoSize.h"
#import "UIImageView+WebCache.h"
#import "LBNewsModel.h"
#import <YYModel.h>
#import "WKNiuwaVideoDetailVC.h"
#import "WKNiuwaTuwenVC.h"
#import "WKHotmenModel.h"
#import "DemoVC2Cell.h"
@interface LBNiuStudentDetailVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@property (nonatomic, strong) UIButton *followBtn;//关注按钮
//@property (nonatomic, strong) UILabel *nickLab;/**昵称*/
//@property (nonatomic, strong) UILabel *nameLab;/**名字*/
//@property (nonatomic, strong) UILabel *brithdayLab;/**生日*/
@property (nonatomic, strong) NSString *isAtten;/**关注状态 1 已关注 0 未关注*/

@end

@implementation LBNiuStudentDetailVC
static NSString *const cellId = @"DemoVC2Cell";
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 150, ScreenW, ScreenH-150) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self setupRefresh];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationItem.title = @"牛娃详情";
    [self setupUI];

}
//刷新
- (void)setupRefresh
{   //下拉
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;
    [self setupData];
}
//决定footer的状态
- (void)checkFooterState{
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}
- (void)setupData{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    
    NSMutableDictionary *dic = @{@"attenUserId":self.attenUserId,@"token":[UserModel getUserModel].token,@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    VKWeakSelf(self)
    
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKQueryGoodChildClock_WKURL withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.dataArray removeAllObjects];
            }
            
            NSString *isAtten = [NSString stringWithFormat:@"%@",result[@"data"][@"isAtten"]];
            self.isAtten = isAtten;
            NSArray *arr = [WKHotmenModel mj_objectArrayWithKeyValuesArray:result[@"data"][@"clockRecordVOS"]];
            [self.dataArray addObjectsFromArray:arr];
            if ([isAtten isEqualToString:@"1"]) {
                [self.followBtn setTitle:@"取消关注" forState:UIControlStateNormal];
            }else{
                [self.followBtn setTitle:@"关注" forState:UIControlStateNormal];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
//            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)BackAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setupUI{
    UIView *topView = [UIView new];
    [self.view addSubview:topView];
    topView.frame = CGRectMake(0, 0, ScreenW, 150*kScaleFit);
    topView.backgroundColor = rgb(233,84,18);

    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(20*kScaleFit, 30*kScaleFit, 20*kScaleFit, 25*kScaleFit);
    [btn addTarget:self action:@selector(BackAction) forControlEvents:(UIControlEventTouchUpInside)];
    [btn setImage:[UIImage imageNamed:@"wk_back_white"] forState:(UIControlStateNormal)];
    [btn setImage:[UIImage imageNamed:@"wk_back_white"] forState:(UIControlStateHighlighted)];
    [topView addSubview:btn];
    
    
    UIImageView *icon = [[UIImageView alloc] init];
    icon.layer.cornerRadius = 37.5;
    icon.layer.masksToBounds = YES;
    icon.layer.borderWidth = 1;
    icon.layer.borderColor = [UIColor whiteColor].CGColor;
    icon.image = [UIImage imageNamed:@"wk_list_bgimg"];

    UIImage *image;
    if ([self.sex isEqualToString:@"0"]) {
        image = [UIImage imageNamed:@"vkgirl"];
    }else{
        image = [UIImage imageNamed:@"vkboy"];
    }
    [icon sd_setImageWithURL:[NSURL URLWithString:self.headImg] placeholderImage:image];
    [topView addSubview:icon];
    [icon makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(75*kScaleFit, 75*kScaleFit));
        make.top.left.mas_equalTo(56*kScaleFit);
        
    }];
    
    UIImageView *vipImageV = [[UIImageView alloc]init];
    vipImageV.image = [UIImage imageNamed:@"wk_vip"];
    vipImageV.contentMode = UIViewContentModeScaleAspectFill;
    vipImageV.clipsToBounds = YES;
    //    _vipImageV = vipImageV;
    [topView addSubview:vipImageV];
    vipImageV.userInteractionEnabled = NO;
    vipImageV.layer.cornerRadius = 7.5;
    vipImageV.layer.masksToBounds = YES;
    [vipImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(icon).offset(0);
        make.size.mas_equalTo(CGSizeMake(15, 15));
        make.bottom.mas_equalTo(icon);
    }];
    if ([self.isVip integerValue]==1) {
        vipImageV.hidden = NO;
    }else{
        vipImageV.hidden = YES;
    }
    
    UILabel *nickLab = [UILabel labelWithText:@"小苹果♂" andTextColor:rgb(255,255,255) andName:nil andFontSize:15*kScaleFit];
//    self.nickLab = nickLab;
    nickLab.text = self.babyNickname;
    [topView addSubview:nickLab];
    [nickLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(icon.mas_top);
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(30*kScaleFit);
    }];
    
    UILabel *nameLab = [UILabel labelWithText:@"王子涵  3岁" andTextColor:rgb(255,255,255) andName:nil andFontSize:12*kScaleFit];
    nameLab.text = [NSString stringWithFormat:@"%@ %@岁",self.babyUsername,self.ageYear];
    
    [topView addSubview:nameLab];
    [nameLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(nickLab.mas_bottom).mas_equalTo(3*kScaleFit);
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(30*kScaleFit);
    }];
    
    UILabel *brithdayLab = [UILabel labelWithText:@"20180105006" andTextColor:rgb(255,255,255) andName:nil andFontSize:12*kScaleFit];
    brithdayLab.text = self.studyNum;
    [topView addSubview:brithdayLab];
    [brithdayLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(nameLab.mas_bottom).mas_equalTo(3*kScaleFit);
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(30*kScaleFit);
    }];
    
    UILabel *deacLab = [UILabel labelWithText:@"一句话证明你最可爱的小孩" andTextColor:rgb(255,255,255) andName:nil andFontSize:12*kScaleFit];
    deacLab.text = self.babyInfo;
    [topView addSubview:deacLab];
    [deacLab makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(brithdayLab.mas_bottom).mas_equalTo(3*kScaleFit);
        make.left.mas_equalTo(icon.mas_right).mas_equalTo(30*kScaleFit);
    }];
    
    UIButton *followBtn = [[UIButton alloc] init];
    self.followBtn = followBtn;
    [followBtn setTitle:@"关注" forState:UIControlStateNormal];
    followBtn.titleLabel.font = [UIFont systemFontOfSize:12*ScaleX];
    [followBtn setTitleColor:rgb(233,84,18) forState:UIControlStateNormal];
    followBtn.layer.cornerRadius = 12;
    followBtn.layer.masksToBounds = YES;

    followBtn.backgroundColor = [UIColor whiteColor];
    [followBtn addTarget:self action:@selector(clickFollowBtn:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:followBtn];
    [followBtn makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(65*ScaleX, 24*ScaleX));
        make.right.mas_equalTo(-30*ScaleX);
        make.bottom.mas_equalTo(brithdayLab.mas_bottom);
    }];
    [self.view addSubview:self.tableView];

    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
         self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    self.tableView.tableFooterView = [UIView new];
}
- (void)clickFollowBtn:(UIButton *)sender{
    NSLog(@"点击了关注按钮");

    NSString *token = [UserModel getUserModel].token;
    if ([self.isAtten isEqualToString:@"1"]) {
        [WYHXNetWorkManager post:WKCancelFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":self.attenUserId} completionHandler:^(id responseObj, NSError *error) {
//            NSLog(@"%@",responseObj);
            NSString *code = responseObj[@"code"];
            NSString *msg = responseObj[@"msg"];
            if ([code integerValue]==200) {
                self.isAtten = @"0";
                [MBProgressHUD showSuccess:msg toView:self.view];
                [sender setTitle:@"关注" forState:UIControlStateNormal];
                return ;
//                [self setupLoadData];
            }
        }];
    }else{
        [WYHXNetWorkManager post:WKFollowniuwa_WKURL params:@{@"token":token,@"attenUserId":self.attenUserId} completionHandler:^(id responseObj, NSError *error) {
//            NSLog(@"%@",responseObj);
            NSString *msg = responseObj[@"msg"];
            NSString *code = responseObj[@"code"];
            if ([code integerValue]==200) {
//                [self setupLoadData];
                self.isAtten = @"1";
                [sender setTitle:@"取消关注" forState:UIControlStateNormal];
                [MBProgressHUD showSuccess:msg toView:self.view];
            }else if ([code integerValue]==203){
                [MBProgressHUD showSuccess:msg toView:self.view];
                return ;
            }
        }];
    }

    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WKHotmenModel *model = self.dataArray[indexPath.section];
    
    if ([model.fileType isEqualToString:@"2"]) {
        
        WKNiuwaCell *cell = [WKNiuwaCell cellWithTableView:tableView];
        cell.playIcon.hidden = YES;//隐藏中间的播放按钮
        cell.model = model;
        
        
        //点赞按钮
        [cell.zanButton addTarget:self action:@selector(clickImageZanBtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.zanButton.tag = 20223+indexPath.section;
        cell.selectionStyle = UITableViewCellSeparatorStyleNone;
        return cell;
        
    }else{

        DemoVC2Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if(!cell){
            cell = [[DemoVC2Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.followBnt.hidden = YES;

        WKHotclockInfoVOListModel *model2 = model.clockInfoVOList[0];
         NSString *urlstring =[NSString stringWithFormat:@"%@%@",Public_URL,model2.videoCover];
                [cell.imgView sd_setImageWithURL:[NSURL URLWithString:urlstring] placeholderImage:[UIImage imageNamed:@"wk_list_bgimg"]];

        cell.followModel = model;
        cell.zanBtn.tag = 1013+indexPath.section;
        cell.selectionStyle = UITableViewCellSeparatorStyleNone;
        [cell.zanBtn addTarget:self action:@selector(clickVideoZanBtn:) forControlEvents:UIControlEventTouchUpInside];
        
//        return cell;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WKHotmenModel *model = self.dataArray[indexPath.section];
    if ([model.fileType isEqualToString:@"2"]) {
        return 424;
    }else{

        return 424;
    }
}
#pragma mark - 图片类型点赞
- (void)clickImageZanBtn:(UIButton *)sender{
    NSInteger index = sender.tag-20223;
    
    WKHotmenModel *model = self.dataArray[index];
    if ([model.fileType isEqualToString:@"2"]) {
        NSString *token = [UserModel getUserModel].token;
        if ([model.isPrase isEqualToString:@"1"]) {
            [WYHXNetWorkManager post:WKCancelPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    
                    NSLog(@"图片取消点赞====第%ld次",index);
                    //刷新数据
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                    model.isPrase = @"0";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] - 1];
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }else{
            
            [WYHXNetWorkManager post:WKPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //刷新数据
                    //                [self setupLoadData];
                    NSLog(@"图片点赞====第%ld次",index);
                    [MBProgressHUD showSuccess:@"点赞成功" toView:self.view];
                    model.isPrase = @"1";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] + 1];
                    
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }
        
    }
    

}
#pragma mark - 视频类型点赞
- (void)clickVideoZanBtn:(UIButton *)sender{
    NSInteger index = sender.tag-1013;
    
    WKHotmenModel *model = self.dataArray[index];
    
    
    if ([model.fileType isEqualToString:@"2"]) {
        
    }else{
        NSString *token = [UserModel getUserModel].token;
        if ([model.isPrase isEqualToString:@"1"]) {
            [WYHXNetWorkManager post:WKCancelPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //                    NSLog(@"视频取消点赞====第%ld次",index);
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                    model.isPrase = @"0";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] - 1];
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
                //                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            }];
        }else{
            
            [WYHXNetWorkManager post:WKPraiseClock_WKURL params:@{@"token":token,@"clockId":model.clockId} completionHandler:^(id responseObj, NSError *error) {
                //            NSLog(@"%@",responseObj);
                NSString *code = responseObj[@"code"];
                if ([code integerValue]==200) {
                    //刷新数据
                    //                    NSLog(@"视频点赞====第%ld次",index);
                    //                [self setupLoadData];
                    [MBProgressHUD showSuccess:@"点赞成功" toView:self.view];
                    model.isPrase = @"1";
                    model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] + 1];
                    
                    [self.dataArray replaceObjectAtIndex:index withObject:model];
                }else{
                    [MBProgressHUD showSuccess:responseObj[@"msg"] toView:self.view];
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
                //                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                [UIView performWithoutAnimation:^{
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                }];
            }];
        }
        
    }
    

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

        WKHotmenModel *model = self.dataArray[indexPath.section];
    if ([model.fileType isEqualToString:@"1"]) {
        WKNiuwaVideoDetailVC *videoVC = [[WKNiuwaVideoDetailVC alloc] init];
        videoVC.nameTitle = model.username;
        videoVC.model = model;
        [self.navigationController pushViewController:videoVC animated:YES];
    }else{
        WKNiuwaTuwenVC *imageTextVC = [[WKNiuwaTuwenVC alloc] init];
        imageTextVC.nameTitle = model.username;
        imageTextVC.model = model;
        [self.navigationController pushViewController:imageTextVC animated:YES];
    }
}
@end
